# coding: utf-8
import sqlite3

DDL_SQL = ["""
CREATE TABLE monitor_primitive
(
ITEM_ID     INTEGER PRIMARY KEY autoincrement,
ITEM_IP     TEXT NOT NULL,
ITEM_NAME   TEXT NOT NULL,
ITEM_CONTENT TEXT NOT NULL,
ITEM_CREATE_TIME TEXT
);
""", """
CREATE TABLE monitor_meta
(
ITEM_ID          INTEGER PRIMARY KEY autoincrement,
ITEM_IP          TEXT NOT NULL,
ITEM_NAME        TEXT NOT NULL,
ITEM_CREATE_TIME TEXT
);
""", """
CREATE TABLE monitor_alert
(
ITEM_ID          INTEGER PRIMARY KEY autoincrement,
ITEM_IP          TEXT NOT NULL,
ITEM_TYPE        TEXT NOT NULL,
ITEM_CREATE_TIME TEXT
);
""", """
CREATE TABLE monitor_temp
(
ITEM_ID          INTEGER PRIMARY KEY autoincrement,
ITEM_IP          TEXT NOT NULL,
ITEM_TYPE        TEXT NOT NULL,
ITEM_CREATE_TIME TEXT
);
"""]


class SqlTool:
    def __init__(self):
        self.conn = sqlite3.connect('monitor.db')
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.conn.close()

    def init_tables(self):
        for s in DDL_SQL:
            self.cursor.execute(s)
        self.conn.commit()

    def insert_primitive(self, ip, t, content, time):
        item_id = ip + '_' + time
        s = """
        INSERT INTO monitor_primitive VALUES (NULL,'%s','%s','%s','%s')
        """ % (ip, t, content, time)
        self.cursor.execute(s)
        self.conn.commit()

    def insert_index(self, ip, t, ):
        pass

    def insert_alert(self):
        pass


if __name__ == '__main__':
    with SqlTool() as sql:
        sql.init_tables()
